import React, { useEffect, useState, useRef } from 'react';
import styles from './index.less';
import { DatePicker, Select, Button, Space } from 'antd';
import moment from 'moment';
import { connect } from 'umi';

import { TRAlert, TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { programOverview, operateLog } from '@/assets';
import { TjSegmented } from '@/pages/ETrade/components';
import {
  fetchSequences,
  fetchSequencesFuture,
} from '@/pages/Tianji/TenDaysCentralizedBidding/services';
import OperateLogModal from '../OperateLogModal';
import ProgramOverviewModal from '../ProgramOverviewModal';
import { FileTextOutlined, CodeSandboxOutlined } from '@ant-design/icons';

const { Option } = Select;
function Header({
  tradeCenterTime,
  currentProgramInfo,
  tradeSeqId,
  currentProgramId,
  programList,
  hasModified,
  dispatch,
  power = [],
  market = {},
  setFatherState,
}) {
  const [tradingDays, setTradingDays] = useState([]);
  const [station, setStation] = useState(power?.[0] || {});
  const [date, setDate] = useState(null);
  const [type, setType] = useState();

  const operateLogModalRef = useRef();
  const programOverviewRef = useRef();

  useEffect(() => {
    init();
  }, []);

  useEffect(() => {
    if (date && station.marketId) {
      fetchSequencesFunc(station.marketId, date, type);
    }
  }, [date, station.marketId, type]);

  async function fetchSequencesFunc(marketId, date, type) {
    dispatch({
      type: 'tenDaysCentralizedBidding/setAddLoadingNum',
    });
    const res = await fetchSequences(marketId, date.format('YYYY-MM-DD'), type);
    dispatch({
      type: 'tenDaysCentralizedBidding/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (res.data.tradingDays.length) {
        setTradingDays(res.data.tradingDays);
        dispatch({
          type: 'tenDaysCentralizedBidding/setTradeSeqId',
          payload: res.data.tradingDays[0]?.id,
        });
        dispatch({
          type: 'tenDaysCentralizedBidding/setTradeSeqInfo',
          payload: res.data.tradingDays[0],
        });
      } else {
        setTradingDays([]);
        dispatch({
          type: 'tenDaysCentralizedBidding/setTradeSeqId',
          payload: null,
        });
        dispatch({
          type: 'tenDaysCentralizedBidding/setTradeSeqInfo',
          payload: {},
        });
      }
    } else {
      TRMessage.error(res?.message || '获取序列列表信息失败');
    }
  }

  // 获取最近未来有交易序列的日期；如果没有则取当前日期；
  async function fetchSequencesFutureFunc() {
    dispatch({
      type: 'tenDaysCentralizedBidding/setAddLoadingNum',
    });
    const res = await fetchSequencesFuture();
    dispatch({
      type: 'tenDaysCentralizedBidding/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      let date;
      if (res.data?.tradingDays?.length) {
        date = moment(res.data.tradingDays[0].sequenceDate);
      } else {
        date = new moment();
      }
      dispatch({
        type: 'tenDaysCentralizedBidding/setTradeDate',
        payload: date,
      });
      setDate(date);
    } else {
      TRMessage.error(res?.message || '获取未开始申报的序列信息失败');
    }
  }

  const init = () => {
    fetchSequencesFutureFunc();
  };

  const changeTradeSeq = (value, option) => {
    dispatch({
      type: 'tenDaysCentralizedBidding/setTradeSeqId',
      payload: value,
    });
    dispatch({
      type: 'tenDaysCentralizedBidding/setTradeSeqInfo',
      payload: option,
    });
  };

  const lastOperateTime = () => {
    if (!currentProgramInfo?.latestOperateLog) return;
    let operateTime = currentProgramInfo.latestOperateLog.operateTime;
    switch (currentProgramInfo.latestOperateLog.type) {
      case 0:
        return (
          <div className={styles.lastOperateTime}>
            <span className={styles.label}>当前方案新建时间: </span>
            <span>{moment(operateTime).format('YYYY.MM.DD HH:mm:ss')}</span>
          </div>
        );
      case 2:
      case 3:
        return (
          <div className={styles.lastOperateTime}>
            <span className={styles.label}>当前方案最后保存时间: </span>
            <span>{moment(operateTime).format('YYYY.MM.DD HH:mm:ss')}</span>
          </div>
        );
      case 4:
      case 8:
        return (
          <div className={styles.lastOperateTime}>
            <span className={styles.label}>当前方案最后申报时间: </span>
            <span>{moment(operateTime).format('YYYY.MM.DD HH:mm:ss')}</span>
          </div>
        );
    }
  };
  const handleSearch = async () => {
    if (hasModified) {
      let obj = await TRAlert.show('当前工作将不被保存，继续执行此操作？');
      if (obj.index === 0) return;
      dispatch({
        type: 'tenDaysCentralizedBidding/setHasModified',
        payload: false,
      });
    }
    if (tradeSeqId) {
      setFatherState({
        market: station,
      });
      dispatch({
        type: 'tenDaysCentralizedBidding/setFormData',
        payload: {
          date: date?.format('YYYY-MM-DD'),
          marketId: station?.marketId,
          //type
          //tradeSeqId
        },
      });
      dispatch({
        type: 'tenDaysCentralizedBidding/getStationLevelThreeEffect',
        payload: station,
      });
      dispatch({
        type: 'tenDaysCentralizedBidding/setShowMain',
        payload: true,
      });
      dispatch({
        type: 'tenDaysCentralizedBidding/handleSearchEffect',
      });
    } else {
      dispatch({
        type: 'tenDaysCentralizedBidding/setShowMain',
        payload: false,
      });
      TRMessage.warning('当前日期无交易序列，请选择交易日期获取交易序列后，再进行查询');
    }
  };

  return (
    <div className={styles.header}>
      <div className={styles.tradeSeq}>
        <Space size={16}>
          <Select
            className={styles.tradeSeqSelect}
            style={{ width: 160 }}
            value={station.value}
            options={power}
            optionFilterProp="label"
            showSearch
            showArrow
            onChange={(v, opt) => {
              setStation(opt);
              setType(v === 'PHBSD' ? 'month' : '');
            }}
          />
          <DatePicker
            className={`border-radius-5 ${styles.dataPicker}`}
            allowClear={false}
            onChange={(e) => {
              dispatch({
                type: 'tenDaysCentralizedBidding/setTradeDate',
                payload: e,
              });
              setDate(e);
            }}
            value={date}
            format="YYYYMMDD"
          />
          {station?.marketId === 'PHBSD' ? (
            <TjSegmented
              value={type}
              options={[
                { label: '月度', value: 'month' },
                { label: '月内', value: 'in_month' },
              ]}
              onChange={(e) => {
                setType(e);
              }}
            />
          ) : (
            ''
          )}
          <Select
            className={styles.tradeSeqSelect}
            style={{ width: 320 }}
            value={tradeSeqId}
            onChange={changeTradeSeq}
          >
            {tradingDays.map((item) => {
              return (
                <Option value={item.id} key={item.id}>
                  {item.sequenceTitle}
                </Option>
              );
            })}
          </Select>
          <Button type="primary" onClick={handleSearch}>
            查询
          </Button>
        </Space>
      </div>
      {tradeCenterTime ? (
        <div className={styles.tradeCenterTime}>
          <span className={styles.time}>{moment(tradeCenterTime).format('HH:mm:ss')}</span>
          <div className={styles.dateAndWeek}>
            <span>{moment(tradeCenterTime).format('YYYY年MM月DD日')}</span>
            <span>{moment(tradeCenterTime).format('dddd')}</span>
          </div>
        </div>
      ) : (
        ''
      )}

      <div className={styles.right}>
        {currentProgramId && currentProgramId !== '-1' ? lastOperateTime() : ''}
        {programList.length ? (
          <div
            className={styles.programOverview}
            onClick={() => {
              programOverviewRef.current.initHandle();
            }}
          >
            {/* <img className={styles.icon} src={programOverview} /> */}
            <CodeSandboxOutlined className={styles.icon} />
            <span>待申报方案总览</span>
          </div>
        ) : (
          ''
        )}
        {programList.length ? (
          <div
            className={styles.operateLog}
            onClick={() => {
              operateLogModalRef.current.initHandle();
            }}
          >
            <FileTextOutlined className={styles.icon} />
            <span>操作日志</span>
          </div>
        ) : (
          ''
        )}
      </div>
      <OperateLogModal ref={operateLogModalRef} market={market} />
      <ProgramOverviewModal ref={programOverviewRef} market={market} />
    </div>
  );
}

export default connect(({ tenDaysCentralizedBidding }) => ({
  tradeCenterTime: tenDaysCentralizedBidding.tradeCenterTime,
  tradeSeqId: tenDaysCentralizedBidding.tradeSeqId,
  currentProgramInfo: tenDaysCentralizedBidding.currentProgramInfo,
  currentProgramId: tenDaysCentralizedBidding.currentProgramId,
  programList: tenDaysCentralizedBidding.programList,
  hasModified: tenDaysCentralizedBidding.hasModified,
}))(Header);
